package com.tanhua.dubbo.server.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tanhua.dubbo.server.config.HuanXinConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class TokenService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private HuanXinConfig huanXinConfig;

    private static final String REDIS_KEY = "HX_TOKEN";

    /**
     * 获取环信的token
     *
     * @return
     */
    public String getToken() {
        String tokenKey = REDIS_KEY;
        String token = redisTemplate.opsForValue().get(tokenKey);
        if (StrUtil.isNotEmpty(token)) {
            return token;
        }
        return refreshToken();
    }

    public String refreshToken() {
        String url = huanXinConfig.getUrl() + huanXinConfig.getOrgName() + "/" + huanXinConfig.getAppName() + "/token";
        Map<String, Object> param = new HashMap<>();
        param.put("grant_type", "client_credentials");
        param.put("client_id", huanXinConfig.getClientId());
        param.put("client_secret", huanXinConfig.getClientSecret());

        String data = JSONUtil.toJsonStr(param);
        HttpResponse response = HttpRequest.post(url).body(data).timeout(20000).execute();

        if (!response.isOk()) {
            return null;
        }
        String body = response.body();
        JSONObject jsonObject = JSONUtil.parseObj(body);
        String token = jsonObject.getStr("access_token");
        if (StrUtil.isNotEmpty(token)) {
            long expires = jsonObject.getLong("expires_in") - 3600;
            redisTemplate.opsForValue().set(REDIS_KEY, token, expires, TimeUnit.SECONDS);
            return token;
        }
        return null;
    }
}
